package controller

import (
	"GoTime/models"
	"GoTime/response"
	. "GoTime/utils"
	"crypto/x509"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"golang.org/x/crypto/pkcs12"
	"xorm.io/builder"
)

var (
	deleteerror string = "删除信息失败"
	pix                = "MIINXAIBAzCCDRYGCSqGSIb3DQEHAaCCDQcEgg0DMIIM/zCCBXQGCSqGSIb3DQEHAaCCBWUEggVhMIIFXTCCBVkGCyqGSIb3DQEMCgECoIIE+jCCBPYwKAYKKoZIhvcNAQwBAzAaBBQP4innfQOawvG/MgfE5kykENFxKgICBAAEggTIwCArIcZdhiFPDwBNjLGCOCwUdDccoyMXfhCExCli0xliqT+m3qUDLJ1wNzYg0xhg9Pxm84YYyOQS8C+UTJayZpmlIUIg+JM50EHw98vBbhaWpV2UT6tIH8dyy4D9pXgzKBsxo9EHOBU6AhznI4aDWtdoNDeo6A56xJW0QsKw428vQ4YR9A0REC0jAsnVDJppyhLMTUUZ/7u1DTKqzKHLCqnpsfTGyinEd1tTluwT9YeGNW2IJNIMTjdxtIvSwaKX3xBk+iHdCIacgsovzjaWIT2tPVTMXH507QtaBDd7+8LVQhyeUr5CqHm50XbM7wozOxbzhVI0mTqUwFu5NdLn9c3Gmhj+3i4hewXcJ3XTEgXg9bAeyIM2R8d5zQqfK+SGbbcp1e5Qe8Zv4I4FkeYXrafg0QWAqJgp6fJQTMEd7GbcNYjnElLy23c9UIXQRvqbPCP/sffP8s+87dweg37A+mh7lNFfhuD39kXosriOQfFcdmOhF9lPTTkSFVUqC8a+Bs1Rfq+LXXnjemoL8FPM4KYSFiZXLIktnF8JA6SuwfJ4eHnAAWnO1tkPpSJuiAZ2bsKwAbY8wASlOLUwtRpjhUZshBZSikOtN29fotfytHyE8KCXqWMYFuVtGhc/hk08JK2H/sHqpA9SNsi5o5VKp9FgNp4geDU9HzrV0tCWDjGXlmwRlxMuHj776SfSb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5rqTxrLO5e+W3d9tz7Vj72xXaIj4X7jdKy/6fmxqOcVJEVcMVbbGk5xqnUXeeEMsJWCgkFrNQXYPU90EujYn/LhNI2IQaoz+tTaZeTdYe6NUAiTJ9BwA8dDdCXaw/p3p1wrfROAX1xOiEXFCx164l0X9utbUIaFMtyTuyAeJBm9OYXQItM2SuOwG5bCa+5pMKxxo7JWrrkp/ZcBbYPQOY5v1CR/1gltyI62dy9ps8QgsSMoP950RZ0IBuYYg4xpJ5SAr9x4DWaFPSSVn2/utKk5UX8GDzxyhV5bq8cxfAqIHZo1p2wias0CP9s3ZwFXjebBZDpVxHJ2GF272/zNzA9MCEwCQYFKw4DAhoFAAQUhOjaSQt0fne5t0AuQvr146CE8doEFJMA13P/zjypbvjCRqMR4yMwQvLMAgIEAA=="
	pin                = "27U777"
)

func GetTerminalList(c *gin.Context) {
	var (
		terminalList []response.TerminalListResponse
		err          error
		page         int
		pageSize     int
		offset       int
		count        int64
	)
	page = cast.ToInt(c.DefaultQuery("page", "0"))
	pageSize = cast.ToInt(c.DefaultQuery("pageSize", "10"))
	offset = (page - 1) * pageSize
	filter := builder.NewCond()
	filter = filter.And(builder.Eq{"t.school_id": c.Query("school_id")})
	if installDate := c.Query("installstartdate"); installDate != "" {
		filter = filter.And(builder.Gte{"t.install_date": installDate})
	}
	if installEnDate := c.Query("installenddate"); installEnDate != "" {
		filter = filter.And(builder.Lte{"t.install_date": installEnDate})
	}
	if imei := c.Query("imei"); imei != "" {
		filter = filter.And(builder.Like{"t.imei", imei})
	}
	if plateNumber := c.Query("plate_number"); plateNumber != "" {
		filter = filter.And(builder.Like{"c.plate_number", plateNumber})
	}
	if terminalType := c.Query("type"); terminalType != "" {
		filter = filter.And(builder.Eq{"t.type": terminalType})
	}
	count, terminalList, err = new(models.Terminal).GetTerminalList(filter, pageSize, offset)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "获取终端列表失败", "data": err})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "获取终端列表成功", "data": gin.H{"count": count, "terminalList": terminalList}})
	return
}

func AddTerminal(c *gin.Context) {
	terminal := new(models.Terminal)
	var (
		err error
	)
	if terminal, _ = new(models.Terminal).GetTerminalByImei(c.PostForm("imei")); terminal.Id > 0 {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "该IMEI已经存在"})
		return
	}
	if err = c.ShouldBind(terminal); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "参数错误"})
		return
	}
	if terminal.InstallDate, err = time.Parse("2006-01-02", c.PostForm("install_date")); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "安装日期格式错误"})
		return
	}
	if len(terminal.Imei) != 15 {
		fmt.Println(len(terminal.Imei))
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "请输入15位的有效数字"})
		return
	}
	terminal.TerminalGroupId = 1
	terminal.Isused = "1"
	terminal.InstitutionCode = GetInstitutionCode(terminal.Imei)
	terminal.Certificate = pix
	terminal.CertificateKey = pin
	terminal.RecordStatus = "0"
	terminal.ApprovalStatus = "1"
	// 获取数据库引擎实例
	var engine = models.Engine

	// 创建一个新的数据库会话
	var session = engine.NewSession()

	// 确保在函数结束时关闭会话
	defer session.Close()

	// 开始一个数据库事务
	if err := session.Begin(); err != nil {
		// 如果事务开始失败，返回错误信息
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "事务开始失败", "data": err.Error()})
		return
	}
	if _, err = session.Insert(terminal); err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "添加终端失败"})
		return
	}
	session.Commit()
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "添加终端成功"})
	return
}

func RecordTerminal(c *gin.Context) {
	var (
		pfxData []byte
		cert    *x509.Certificate
		err     error
		retMap  map[string]interface{}
		url     string
	)
	// 获取请求中的场地ID参数
	if terminalId := c.Query("terminal_id"); terminalId == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "缺少设备ID"})
		return
	}
	ok, school, err := new(models.School).GetSchoolById(cast.ToInt(c.Query("school_id")))
	if err != nil || !ok {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "驾校不存在"})
		return
	}
	terminal := new(models.Terminal).GetTerminalById(c.Query("terminal_id"))
	if terminal == nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "终端不存在"})
		return
	}
	if terminal.Certificate == "" || terminal.CertificateKey == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "终端证书为空"})
		return
	}
	if pfxData, err = base64.StdEncoding.DecodeString(terminal.Certificate); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err})
		return
	}
	if _, cert, err = pkcs12.Decode(pfxData, terminal.CertificateKey); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err})
		return
	}
	data := map[string]interface{}{
		"devnum":    terminal.InstitutionCode,                    //终端编号
		"termtype":  terminal.Type,                               //计时终端类型
		"vender":    terminal.Brand,                              //生产厂家
		"model":     terminal.TerminalSerial,                     //终端型号
		"imei":      terminal.Imei,                               //终端IMEI号或设备MAC地址
		"sn":        terminal.SerialCode,                         //终端出厂序列号
		"inscode":   school.InstitutionCode,                      //培训机构编号
		"cerbase64": base64.StdEncoding.EncodeToString(cert.Raw), //终端公钥
	}
	if terminal.Type == "3" || terminal.Type == "4" {
		data["devlevel"] = "02"
		if school.Province == "420000" {
			data["traincarmodel"] = "C"
			data["transmission"] = "M"
		}
	}
	if url, err = GetSignURL("device", data, 2, school.Province, school.City); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err})
		return
	}
	var api_log models.ApiLog
	param, err := json.Marshal(data)
	api_log.Url = url
	api_log.Param = string(param)
	api_log.Method = "POST"
	api_log.UserId = school.UserId
	api_log.Time = time.Now()
	if retMap, err = APIReq(url, data, "POST"); err != nil {
		result, _ := json.Marshal(retMap)
		api_log.Result = string(result)
		api_log.Add()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err})
		return
	}
	result, _ := json.Marshal(retMap)
	api_log.Result = string(result)
	api_log.Add()
	fmt.Println(retMap)
	errorcode, _ := cast.ToFloat64E(retMap["errorcode"])
	if errorcode != 0 && !strings.Contains(retMap["message"].(string), "已经备案") {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": retMap["message"].(string)})
		return
	}
	//备案成功后将本地数据库备案状态修改为1
	terminal.RecordStatus = "1"
	// 获取数据库引擎实例
	var engine = models.Engine
	// 创建一个新的数据库会话
	var session = engine.NewSession()
	// 确保在函数结束时关闭会话
	defer session.Close()
	// 开始一个数据库事务
	if err := session.Begin(); err != nil {
		// 如果事务开始失败，返回错误信息
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "事务开始失败", "data": err.Error()})
		return
	}
	if _, err = session.ID(terminal.Id).Cols("record_status").Update(terminal); err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "更新终端备案状态失败"})
		return
	}
	session.Commit()
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "终端备案成功"})
	return
}

func EditTerminal(c *gin.Context) {
	//ok, school, err := new(models.School).GetSchoolById(cast.ToInt(c.PostForm("school_id")))
	//if err != nil || !ok {
	//	c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "驾校不存在"})
	//	return
	//}
	terminal := new(models.Terminal).GetTerminalById(c.PostForm("terminal_id"))
	if terminal == nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "终端不存在"})
		return
	}
	terminalCar, err := new(models.TerminalCar).GetOneTerminalCarByTerminalId(terminal.Id)
	if terminalCar.Id > 0 {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "该设备已绑定，请先解绑后修改"})
		return
	}
	if err = c.ShouldBind(terminal); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "解析错误"})
		return
	}
	if terminal.InstallDate, err = time.Parse("2006-01-02", c.PostForm("install_date")); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "解析错误"})
		return
	}
	terminal.RecordStatus = "0"
	if terminal.InstitutionCode == "" {
		terminal.InstitutionCode = GetInstitutionCode(terminal.Imei)
	}
	// 获取数据库引擎实例
	var engine = models.Engine
	// 创建一个新的数据库会话
	var session = engine.NewSession()
	// 确保在函数结束时关闭会话
	defer session.Close()
	// 开始一个数据库事务
	if err := session.Begin(); err != nil {
		// 如果事务开始失败，返回错误信息
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "事务开始失败", "data": err.Error()})
		return
	}
	if _, err = session.ID(terminal.Id).Cols("institution_code", "flameout", "type", "brand", "terminal_serial", "install_date", "record_status").Update(terminal); err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "修改终端失败"})
		return
	}
	session.Commit()
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "修改终端成功"})
	return
}

func DeleteTerminal(c *gin.Context) {
	var (
		url      string
		terminal *models.Terminal
		err      error
		retMap   map[string]interface{}
		reqType  int64
	)
	// 获取请求中的场地ID参数
	if terminalId := c.Query("terminal_id"); terminalId == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "缺少设备ID"})
		return
	}
	terminal = new(models.Terminal).GetTerminalById(c.Query("terminal_id"))
	ok, school, err := new(models.School).GetSchoolById(cast.ToInt(c.Query("school_id")))
	if err != nil || !ok {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "驾校不存在"})
		return
	}
	if url, err = GetSignURL("device-"+terminal.InstitutionCode, nil, reqType, school.Province, school.City); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err})
		return
	}
	// NOTE: 武汉市 接口方法为 GET
	apiMethod := "DELETE"
	isWuHan := school.City == "420100"
	shanDong := school.Province == "370000"
	anHui := school.Province == "340000"
	if isWuHan || shanDong || anHui {
		apiMethod = "GET"
	}
	var apiLog models.ApiLog
	apiLog.Url = url
	apiLog.Param = ""
	apiLog.Method = apiMethod
	apiLog.Time = time.Now()
	if retMap, err = APIReq(url, nil, apiMethod); err != nil {
		result, _ := json.Marshal(retMap)
		apiLog.Result = string(result)
		apiLog.Add()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "删除终端失败"})
		return
	}
	result, _ := json.Marshal(retMap)
	apiLog.Result = string(result)
	apiLog.Add()
	errorcode, _ := cast.ToFloat64E(retMap["errorcode"])
	if errorcode != 0 && !strings.Contains(retMap["message"].(string), "已经备案") {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": retMap["message"].(string)})
		return
	}
	terminal.Isused = "0"
	terminal.Hisimei = terminal.Imei
	terminal.Imei = ""
	terminal.Remark = terminal.InstitutionCode
	terminal.InstitutionCode = ""
	// 获取数据库引擎实例
	var engine = models.Engine
	// 创建一个新的数据库会话
	var session = engine.NewSession()
	// 确保在函数结束时关闭会话
	defer session.Close()
	// 开始一个数据库事务
	if err := session.Begin(); err != nil {
		// 如果事务开始失败，返回错误信息
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "事务开始失败", "data": err.Error()})
		return
	}
	if _, err = session.ID(terminal.Id).Cols("isused", "hisimei", "imei", "institution_code", "remark").Update(terminal); err != nil {
		session.Rollback()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "修改终端失败"})
		return
	}
	session.Commit()
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "删除终端成功"})
	return
}

func BindingCar(c *gin.Context) {
	var (
		terminal *models.Terminal
		has      bool
		url      string
		retMap   map[string]interface{}
	)
	// 获取请求中的场地ID参数
	if terminalId := c.PostForm("terminal_id"); terminalId == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "缺少设备ID"})
		return
	}
	if schoolId := c.PostForm("school_id"); schoolId == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "缺少驾校ID"})
		return
	}
	if sim := c.PostForm("sim"); sim == "" || (len(sim) != 11 && len(sim) != 13) {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "请检查sim卡号"})
		return
	}
	if carNumber := c.PostForm("car_number"); carNumber == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "请检查车牌号"})
		return
	}
	terminal = new(models.Terminal).GetTerminalById(c.PostForm("terminal_id"))
	ok, school, err := new(models.School).GetSchoolById(cast.ToInt(c.PostForm("school_id")))
	if err != nil || !ok {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "驾校不存在"})
		return
	}
	if has, _, err = new(models.TerminalCar).GetTerCarInfoByTerSim(c.PostForm("sim")); has {
		c.JSON(200, gin.H{"code": 201, "msg": "Sim卡已被使用", "data": nil})
		return
	}
	car, err := new(models.Car).GetOneCarByCarNumber(c.PostForm("car_number"))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "车辆不存在"})
		return
	}
	data := map[string]interface{}{
		"devnum": terminal.InstitutionCode, //终端编号
		"carnum": car.InstitutionCode,      //车辆编号
		"sim":    c.PostForm("sim"),        //终端SIM卡号
	}
	if url, err = GetSignURL("devassign", data, 2, school.Province, school.City); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	var api_log models.ApiLog
	param, err := json.Marshal(data)
	api_log.Url = url
	api_log.Param = string(param)
	api_log.Method = "POST"
	api_log.UserId = school.UserId
	api_log.Time = time.Now()
	if retMap, err = APIReq(url, data, "POST"); err != nil {
		result, _ := json.Marshal(retMap)
		api_log.Result = string(result)
		api_log.Add()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	result, _ := json.Marshal(retMap)
	api_log.Result = string(result)
	api_log.Add()
	fmt.Println(retMap)
	errorCode, _ := cast.ToFloat64E(retMap["errorcode"])
	if errorCode != 0 {
		if strings.Contains(retMap["message"].(string), "已经被绑定") {
			temp := strings.Replace(retMap["message"].(string), "已经被绑定", "", -1)
			if temp == terminal.InstitutionCode {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
				return
			}
		}
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": retMap["message"]})
		return
	}
	// 获取数据库引擎实例
	var engine = models.Engine
	// 创建一个新的数据库会话
	var session = engine.NewSession()
	// 确保在函数结束时关闭会话
	defer session.Close()
	// 开始一个数据库事务
	if err := session.Begin(); err != nil {
		// 如果事务开始失败，返回错误信息
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "事务开始失败", "data": err.Error()})
		return
	}
	terminalCar := new(models.TerminalCar)
	if get, _ := session.Table("dts_terminal_car").Where("terminal_id = ?", terminal.Id).Get(terminalCar); get {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "该设备已绑定请先解绑后绑定"})
		return
	} else {
		assign := models.TerminalCar{
			CarId:        car.Id,
			TerminalId:   terminal.Id,
			Sim:          c.PostForm("sim"),
			RecordStatus: "1",
			Reged:        "0",
		}

		if _, err := session.Table("dts_terminal_car").Insert(assign); err != nil {
			session.Rollback()
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
			return
		}
		session.Commit()
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "绑定成功"})
	return
}

func UnBindingCar(c *gin.Context) {
	var (
		terminal   *models.Terminal
		err        error
		car        *models.Car
		assign     models.TerminalCar
		url        string
		retMap     map[string]interface{}
		schoolId   string
		terminalId string
	)
	if terminalId = c.PostForm("terminal_id"); terminalId == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "缺少设备ID"})
		return
	}
	if schoolId = c.PostForm("school_id"); schoolId == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "缺少驾校ID"})
		return
	}
	if terminal = new(models.Terminal).GetTerminalById(terminalId); terminal == nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "终端不存在"})
		return
	}
	ok, school, err := new(models.School).GetSchoolById(schoolId)
	if err != nil || !ok {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "驾校不存在"})
		return
	}
	if assign, err = new(models.TerminalCar).GetOneTerminalCarByTerminalId(terminal.Id); err != nil || assign.Id == 0 {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "该设备未绑定车辆"})
		return
	}
	if car, err = new(models.Car).GetOneCarById(assign.CarId); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	data := map[string]interface{}{
		"devnum": terminal.InstitutionCode, //终端编号
		"carnum": car.InstitutionCode,      //车辆编号
		"sim":    assign.Sim,               //终端SIM卡号
	}
	//进行解绑
	if url, err = GetSignURL("devRembinding", data, 2, school.Province, school.City); err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	var apiLog models.ApiLog
	param, err := json.Marshal(data)
	apiLog.Url = url
	apiLog.Param = string(param)
	apiLog.Method = "POST"
	apiLog.UserId, _ = strconv.Atoi(c.PostForm("user_id"))
	apiLog.Time = time.Now()
	if retMap, err = APIReq(url, data, "POST"); err != nil {
		result, _ := json.Marshal(retMap)
		apiLog.Result = string(result)
		apiLog.Add()
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	result, _ := json.Marshal(retMap)
	apiLog.Result = string(result)
	apiLog.Add()
	fmt.Println(retMap)
	errorcode, _ := cast.ToFloat64E(retMap["errorcode"])
	if errorcode != 0 {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": retMap["message"]})
		return
	}
	//解绑成功后删除本地数据库记录
	if !assign.Delete() {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "解绑成功"})
	return
}
